package cn.cqvie.security;

import cn.cqvie.common.BaseContext;
import cn.cqvie.common.R;
import cn.cqvie.pojo.Employee;
import cn.cqvie.service.impl.EmployeeDetailService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class WebSecurity extends WebSecurityConfigurerAdapter {
    @Autowired
    private EmployeeDetailService employeeDetailService;

    @Bean
    public LoginFilter loginFilter() throws Exception {
        LoginFilter loginFilter = new LoginFilter();
        loginFilter.setUsernameParameter("username");
        loginFilter.setPasswordParameter("password");
        loginFilter.setFilterProcessesUrl("/login");
        loginFilter.setAuthenticationManager(authenticationManagerBean());

        loginFilter.setAuthenticationSuccessHandler((req,resp,au)->{
            R<Employee> r = new R<>();
            r.setCode(1);
            r.setMsg("登录成功");
            r.setData((Employee) au.getPrincipal());
            resp.setContentType("application/json;charset=utf-8");
            String s = new ObjectMapper().writeValueAsString(r);
            resp.getWriter().write(s);
        });
        loginFilter.setAuthenticationFailureHandler((req,resp,ex)->{
            R<Employee> r = new R<>();
            R.error("登录失败");
            r.setCode(0);
            r.setMsg("登录失败:"+ex.getMessage());
            resp.setContentType("application/json;charset=utf-8");
            String s = new ObjectMapper().writeValueAsString(r);
            resp.getWriter().write(s);
        });
        return loginFilter;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(employeeDetailService);
    }
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint((req,resp,ex)->{
                    resp.sendRedirect("/backend/login.html");
                    resp.getWriter().write("请登录后访问");
                    resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                })
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(new LogoutSuccessHandlerSecurity())
                .and().authorizeRequests()
                .antMatchers("/*","/img/*","/util/*","/backend/login.html","/backend/img/**","/backend/js/**","/backend/plugin/**","/backend/style/**","/login").permitAll()
                .antMatchers("/backend/page/*").authenticated()
                .and().csrf().disable();
        http.headers().frameOptions().sameOrigin();
        http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}
